var eat=0;
var score=0;
var userInfo={
    "userName": "Linda",
    "again": false
};
// new_element=document.createElement("script");
// new_element.setAttribute("type","text/javascript");
// new_element.setAttribute("src","js/index.js");// 在这里引入了a.js
// document.body.appendChild(new_element);

//游戏后台发送数据
function moveFunc(curVector) {
    console.log(curVector);
    joyStickSnd(curVector);
}

function Adapter(arg) {
    var self = this;
    arg = arg || { is_debug: true };
    var is_debug = arg.hasOwnProperty('is_debug') ? arg.is_debug : false;
    self.debug = new Debug(is_debug);
    self.setRem = function (designWidth, designHeight) {
        designWidth = designWidth || 640;
        designHeight = designHeight || 1136;
        var doc = document.documentElement;
        var width = window.innerWidth || doc.getBoundingClientRect().width;
        var height = window.innerHeight || doc.getBoundingClientRect().height;
        self.debug.log(width, height);
        self.rem = width / (designWidth / 100) < height / (designHeight / 100) ? width / (designWidth / 100) : height / (designHeight / 100);
        doc.style.fontSize = self.rem + "px";
        self.debug.info('setRem complete: rem = ' + self.rem + 'px');
    };
    self.initRem = function () {
        self.setRem();
        window.addEventListener("resize", self.setRem, false);
    };
    self.randomString = function (length) {
        length = length || 16;
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }return text;
    };
    self.getQueryString = function (key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var result = window.location.search.substr(1).match(reg);
        console.log(result ? decodeURIComponent(result[2]) : null);
        return result ? decodeURIComponent(result[2]) : null;
    };
}

function Debug(is_debug) {
    var self = this;
    self.debug = is_debug;
    self.log = function (content) {
        if (self.debug) console.log.apply(console, arguments);
    };
    self.info = function (content) {
        if (self.debug) console.log("%c" + content, "color:blue");
    };
    self.warning = function (content) {
        if (self.debug) console.log("%c" + content, "color:green");
    };
    self.error = function (content) {
        if (self.debug) console.log("%c" + content, "color:red");
    };
}



function Preloader(arg) {
    var self = this;
    arg = arg || { is_debug: true };
    var is_debug = arg.hasOwnProperty('is_debug') ? arg.is_debug : false;
    var files = arg.hasOwnProperty('files') ? arg.files : false;
    var complete = arg.hasOwnProperty('complete') ? arg.complete : false;
    var progress = arg.hasOwnProperty('progress') ? arg.progress : false;
    var error = arg.hasOwnProperty('error') ? arg.error : false;
    var fileload = arg.hasOwnProperty('fileload') ? arg.fileload : false;
    var fileprogress = arg.hasOwnProperty('fileprogress') ? arg.fileprogress : false;
    self.debug = new Debug(is_debug);
    self.queue = new createjs.LoadQueue();
    self.complete = function (event) {
        self.debug.log("preload complete");
        if (complete) {
            complete(event);
        }
    };
    self.progress = function (event) {
        self.debug.info("preload progress:" + event.progress);
        if (progress) {
            progress(event.progress);
        }
    };
    self.error = function (event) {
        self.debug.error("preload error:");
        self.debug.log(event);
        if (error) {
            error(event);
        }
    };
    self.fileload = function (event) {
        self.debug.info("preload fileload:" + event.item.id);
        if (fileload) {
            fileload(event);
        }
    };
    self.fileprogress = function (event) {
        self.debug.info(event.item.id + ":" + event.progress);
        if (fileprogress) {
            fileprogress(event);
        }
    };
    self.queue.installPlugin(createjs.Sound);
    self.queue.on("complete", self.complete, this);
    self.queue.on("progress", self.progress, this);
    self.queue.on("error", self.error, this);
    self.queue.on("fileload", self.fileload, this);
    self.queue.on("fileprogress", self.fileprogress, this);
    self.queue.loadManifest(files);
}

// window.onload = function() {
$(document).ready(function () {

    StartFromHere();
    var d_width = 750, d_height = 1206;
    var adapter = new Adapter();
    var debug = new Debug(true);
    var screenMy;
    if(window.screen.height<window.screen.width){
        screenMy='landscape';
    }else {
        screenMy='portrait';
    }
    adapter.initRem();
    $('#share_bg').on('click',function () {
        $('#share_bg').hide();
    });
    // alert('height:'+window.screen.height+'width:'+window.screen.height);
    console.log('height:'+window.screen.height+'width:'+window.screen.width);
    console.log(screenMy);
    $('canvas').height($('body')[0].clientHeight);
    var stage = document.getElementById('canvas');
    createjs.Touch.enable(stage);

    function getAsset(path, is_debug) {
        return is_debug ? path + "?" + adapter.randomString() : path;
    }

    var noCache = false;
    var prefix = "images/";
    var files = [
        {id: "game_json", src: getAsset("images/game.json", noCache)},
        {id: "start_json", src: getAsset("images/start.json", noCache)},
        {id: "timeout_json", src: getAsset("images/timeout.json", noCache)},
        {id: "fail_json", src: getAsset("images/fail.json", noCache)},
        {id: "game", src: getAsset(prefix + "game.png", noCache)},
        {id: "start", src: getAsset(prefix + "start.png", noCache)},
        {id: "timeout", src: getAsset(prefix + "timeout.png", noCache)},
        {id: "fail", src: getAsset(prefix + "fail.png", noCache)}
    ];
    var app = new Application({
        stage: stage,
        debug: debug,
        adapter: adapter,
        designWidth: d_width,
        designHeight: d_height,
        files: files,
        preloadComplete: preloadComplete,
        preloadProgress: preloadProgress
    });
    console.log(screenMy);
    app.fitScreen();
    $('#divide').on('touchstart',function (event) {
        console.log(event);
        // alert('divide') ;
        $(this).addClass('clicked');
        app.config.speed=-1;
        app.sendUserInfo();
        $('#divide').on('touchend',function (event) {
            $(this).removeClass('clicked');
        });
    });

    $('#merge').on('touchstart',function (event) {
        console.log(event);
        // alert('merge') ;
        app.config.speed=1;
        app.sendUserInfo();
        $(this).addClass('clicked');
        $('#merge').on('touchend',function (event) {
            $(this).removeClass('clicked');
        });
    });
    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
        console.log(app.config);

        // app.fitScreen();
        // alert(app.stage.canvas.width);
        if (window.orientation === 180 || window.orientation === 0) {
            app.config.screen="portrait";
            // alert(app.config.screen);
            app.fitScreen();
            // $('#divide').css({"width":"1.6rem","height":"1.6rem"});
            // $('#merge').css({"width":"1.6rem","height":"1.6rem"});
        }
        if (window.orientation === 90 || window.orientation === -90 ){
            app.config.screen="landscape";
            app.fitScreen();
            // $('#divide').css({"width":"2.6rem","height":"2.6rem"});
            // $('#merge').css({"width":"2.6rem","height":"2.6rem"});
        }
    }, false);

    app.preloader = app.preload();
    function preloadComplete(event) {
        app.data = {
            json: {},
            image: {}
        };
        console.log(app.data.json);
        for (var key in app.views) {
            app.data.json[key] = app.preloader.queue.getResult(key + '_json');
            if (app.data.json[key]) {
                app.data.json[key].images[0] = app.preloader.queue.getResult(key);
            }
        }
        $('#loading').hide();
        app.initUI().initialize(60).showView("start");

        // if(app.config.screen=="landscape"){name
        //     $('#name').hide();
        // }else {
        //     $('#name').show();
        // }
    }
    function preloadProgress(progress) {
        $('#bar').css('width', progress * 73.87 + 'vw');
        $('#loadingNum').html(progress*100+'%');
    }
    window.addEventListener("resize", function () {
        setTimeout(function(){
            app.fitScreen();
            app.initUI().initialize(60).showView(app.current.view);
        }, 60);

    }, false);
    function CustomCompareVector(vectorLeft, vectorRight) {//比较方向

        var leftMo = Math.sqrt(Math.pow(vectorLeft.x, 2) + Math.pow(vectorLeft.y, 2));
        var righMo = Math.sqrt(Math.pow(vectorRight.x, 2) + Math.pow(vectorRight.y, 2));
        var angle;
        var cosAngle = (vectorLeft.x * vectorRight.x + vectorLeft.y * vectorRight.y) / (leftMo * righMo );
        if (cosAngle > 1)
            cosAngle = 1;
        angle = Math.acos(cosAngle);
        angle = 180 / Math.PI * angle;
        return angle;
    }



function GetSlideDirection(px, py, mx, my) {

    var x = Math.abs(px-mx);
    var y = Math.abs(py-my);
    var z = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
    var cos = y/z;
    var radina = Math.acos(cos);//用反三角函数求弧度
    var angle = Math.floor(180/(Math.PI/radina));//将弧度转换成角度
    var mo=Math.sqrt(Math.pow(mx,2)+Math.pow(my,2));
    var xaingliang=[x/mo,y/mo];
    if(mx>px&&my>py){//鼠标在第四象限
        angle = 180 - angle;
    }
    if(mx==px&&my>py){//鼠标在y轴负方向上
        angle = 180;
    }
    if(mx>px&&my==py){//鼠标在x轴正方向上
        angle = 90;
    }
    if(mx<px&&my>py){//鼠标在第三象限
        angle = 180+angle;
    }
    if(mx<px&&my==py){//鼠标在x轴负方向
        angle = 270;
    }
    if(mx<px&&my<py){//鼠标在第二象限
        angle = 360 - angle;
    }
    return [angle,xaingliang,z];

}

function Application() {

    var self = this;
    var args = arguments[0];
    this.adapter = args["adapter"];
    this.debug = args["debug"];
    this.is_webgl = false;
    this.stage = this.is_webgl ? new createjs.SpriteStage(args["stage"]) : new createjs.Stage(args["stage"]);
    this.config = {
        preload: {
            is_debug: false,
            files: args["files"],
            complete: args["preloadComplete"],
            progress: args["preloadProgress"],
            error: args["preloadError"],
            fileLoad: args["preloadFileLoad"],
            fileProgress: args["preloadFileProgress"]
        },
        view: "index",
        restart: false,
        name:"",
        grade: 1919,
        eat:10,
        deg: 0,
        win:"win",
        rank:"others",
        score:33,
        eatNums:22,
        time:"1'33",
        speed:0,
        angle:0,
        downX:0,
        downY:0,
        direction_move:0,
        screen:screenMy,
        isCompare:false
    };
    this. lastVector={
        x:0,
        y:0
    };
    this.curVector={
        x:0,
        y:0
    };
    this.current = {
        view: "start",
        restart: false,
        grade: 99,
        speed:1
    };
    this.size = {
        device: {
            height: document.all ? document.getElementsByTagName("html")[0].offsetHeight : window.innerHeight,
            width: document.all ? document.getElementsByTagName("html")[0].offsetWidth : window.innerWidth
        },
        real: {
            height: document.all ? document.getElementsByTagName("html")[0].offsetHeight : window.innerHeight,//
            width: document.all ? document.getElementsByTagName("html")[0].offsetWidth : window.innerWidth
        },
        design: {
            width: args["designWidth"] || 750,
            height: args["designHeight"] || 1206
        }
    };
    this.ratio = (this.size.real.width / this.size.real.height) / (this.size.design.width / this.size.design.height);
    this.views = {
        start: this.is_webgl ? new createjs.SpriteContainer() : new createjs.Container(),
        game: this.is_webgl ? new createjs.SpriteContainer() : new createjs.Container(),
        timeout: this.is_webgl ? new createjs.SpriteContainer() : new createjs.Container(),
        fail: this.is_webgl ? new createjs.SpriteContainer() : new createjs.Container()
    };
    this.fitScreen = function () {
        self.debug.info('fitScreen');
        self.stage.canvas.width = document.all ? document.getElementsByTagName("html")[0].offsetWidth : window.innerWidth;
        self.stage.canvas.height = document.all ? document.getElementsByTagName("html")[0].offsetHeight : window.innerHeight;
        if (!this.is_webgl) {
            // alert(self.config.screen);
            console.log(self.config.screen);
            if(self.config.screen=="portrait"){
                    self.size.design.width=750;
                    self.size.design.height=1206;
                    console.log(self.size.design.width);
            }else {
                    self.size.design.width=1206;
                    self.size.design.height=750;
            }
            var canvas = self.stage.canvas,
                context = canvas.getContext('2d'),
                auto = true,
                devicePixelRatio = window.devicePixelRatio || 1,
                backingStoreRatio = context.webkitBackingStorePixelRatio ||
                    context.mozBackingStorePixelRatio ||
                    context.msBackingStorePixelRatio ||
                    context.oBackingStorePixelRatio ||
                    context.backingStorePixelRatio || 1,
                ratio = devicePixelRatio / backingStoreRatio;
            if (typeof auto === 'undefined') {
                auto = true;
            }
            if (auto && devicePixelRatio !== backingStoreRatio) {
                var oldWidth = canvas.width;
                var oldHeight = canvas.height;
                this.size.real.width = canvas.width = oldWidth * ratio;
                this.size.real.height = canvas.height = oldHeight * ratio;
                canvas.style.width = oldWidth + 'px';
                canvas.style.height = oldHeight + 'px';
                context.scale(ratio, ratio);
                this.size.device.ratio = ratio;
            }
        } else {
            var canvas = self.stage.canvas,
                ratio = 1;
            var oldWidth = canvas.width;
            var oldHeight = canvas.height;
            this.size.real.width = canvas.width = oldWidth * ratio;
            this.size.real.height = canvas.height = oldHeight * ratio;
            canvas.style.width = oldWidth + 'px';
            canvas.style.height = oldHeight + 'px';
            this.stage.updateViewport(this.size.real.width, this.size.real.height);
        }
        console.log(this.config.screen);
        this.ratio = (this.size.real.width / this.size.design.width) < ( this.size.real.height / this.size.design.height) ? (this.size.real.width / this.size.design.width) : ( this.size.real.height / this.size.design.height);
        this.ratioX = (this.size.real.width / this.size.design.width);
        this.ratioY = ( this.size.real.height / this.size.design.height);
        return this;
    };
    this.initialize = function (fps, handleTick, callback) {
        self.debug.info('initialize');
        createjs.Ticker.setFPS(fps || 60);
        createjs.Ticker.addEventListener("tick", handleTick || this.handleTick);
        createjs.Touch.enable(this.stage, true);
        this.stage.mouseEnabled = true;
        if (callback) {
            callback();
        }
        return this;
    };
    this.handleTick = function () {
        self.stage.update();
    };
    this.sendUserInfo=function (userInfo) {
        var data={
            "curVector":{},
            speed:0
        };
        data.curVector=self.curVector;
        data.speed=self.config.speed;
        console.log(data);
        // alert(data.curVector);
        joyStickSnd(data);
    };
    this.showView = function (view) {
        self.config.view = view;
        self.current.view=view;
        if (this.data.json[view]) {
            var container = this.views[view];
            container.removeAllChildren();
            // var bg=this.sprites.start.bg.clone();
            var border_eat=this.sprites.fail.border_eat.clone();
            var border_score=this.sprites.fail.border_score.clone();
            var border_time=this.sprites.fail.border_time.clone();
            if(view=='start'){
                $('#name').show();
            }
            if(view=='game'){
                console.log(this.sprites[view]);
                // container.addChild(bg);
                for (var key in this.sprites[view]) {
                    container.addChild(this.sprites[view][key]);
                }
                var gradeText= new createjs.Text(score, "48px Arial", "#ffffff");
                var eatText= new createjs.Text(eat, "48px Arial", "#ffffff");
                if(self.config.screen=="landscape"){
                    gradeText.initPosition(0.2, 0.158, 0.5, 0.723, self.size.real.width, self.size.real.height, self.ratio, self.ratio);
                    eatText.initPosition(0.85, 0.105, 0.5, 0.723, self.size.real.width, self.size.real.height, self.ratio, self.ratio);
                }else {
                    // var gradeText = new createjs.Text(score, "48px Arial", "#ffffff");
                    gradeText.initPosition(0.3, 0.123, 0.5, 0.723, self.size.real.width, self.size.real.height, self.ratio, self.ratio);
                    // var eatText = new createjs.Text(eat, "48px Arial", "#ffffff");
                    eatText.initPosition(0.78, 0.09, 0.5, 0.723, self.size.real.width, self.size.real.height, self.ratio, self.ratio);
                }
                gradeText.scaleX = self.ratio;
                gradeText.scaleY = self.ratio;
                gradeText.textBaseline = "alphabetic";
                setInterval(function () {
                    eat++;
                    score++;
                    gradeText.text=score;
                    eatText.text=eat;
                },2000);
                container.addChild(gradeText,eatText);
                console.log(container);
                // self.stage.addEventListener('mousedown', function(event) {
                //     self.stage.addEventListener('pressmove', function(e) {
                //         event.preventDefault();
                //         touches = e.nativeEvent.changedTouches;
                //         console.log(e.nativeEvent.changedTouches);
                //         console.log(e.nativeEvent.changedTouches.length);
                //         $('#test').val(touches.length);
                //         for(var i=0;i<=touches.length;i++ ){
                //             console.log(touches[i]);
                //             if(touches.length>=2){
                //                 if(touches[i].identifier==1){
                //                     // alert(touches.length);
                //                     if(touches[1].pageY>=440){
                //                         if(touches[1].pageX<=window.innerWidth/2){
                //                             self.sprites['game']['btn_merge'].alpha=0.7;
                //                             self.config.speed=1;
                //                         }else {
                //                             self.sprites['game']['btn_divide'].alpha=0.7;
                //                             self.config.speed=-1;
                //                         }
                //                         self.sendUserInfo();
                //                     } else {
                //                         if(self.config.screen=='landscape'){
                //                             self.config.downY=self.sprites['game']['btn_move'].y+0.08*self.size.real.height;
                //                         }else {
                //                             self.config.downY=self.sprites['game']['btn_move'].y+0.043*self.size.real.height;
                //                         }
                //                         var btn_move=self.sprites['game']['btn_move'];
                //                         var X,Y;
                //                         var direction=GetSlideDirection( self.config.downX,self.config.downY,e.stageX,e.stageY);
                //
                //                         self.config.angle=direction[0];
                //                         self.config.position=direction[1];
                //                         // alert(direction[2]);
                //                         if(direction[2]<=50){
                //                             btn_move.x=e.stageX;
                //                             btn_move.y=e.stageY;
                //                             // $('#test').val('btn_move2'+touches.length);
                //                         }else {
                //                             btn_move.x=self.config.downX + Math.sin(2*Math.PI / 360*self.config.angle) * 50;
                //                             btn_move.y=self.size.real.height-(self.config.downY+Math.cos(2*Math.PI/360*self.config.angle)*50);
                //                             // $('#test').val('btn_move3'+touches.length);
                //                         }
                //                         X=btn_move.x-self.config.downX;
                //                         Y=btn_move.y-self.config.downY;
                //                         if (self.config.isCompare == false) {
                //                             self.config.isCompare = true;
                //                             self.lastVector.x = X;
                //                             self.lastVector.y = Y;
                //                         } else {
                //                             self.curVector.x = X;
                //                             self.curVector.y = Y;
                //                             self.config.angle=CustomCompareVector(self.lastVector, self.curVector);
                //                             if (self.config.angle>5) {
                //                                 self.lastVector.x = self.curVector.x;
                //                                 self.lastVector.y = self.curVector.y;
                //                                 //出发发送数据：curVector2；
                //                                 self.sendUserInfo();
                //                                 // moveFunc(self.curVector);
                //                                 // console.log("%c" + "现在的度数大于5度了", "color:#DB7093");
                //                             }
                //                         }
                //                         self.config.direction_move=direction[2];
                //                     }
                //                 }
                //             }
                //         }
                //         // alert(touches.length);
                //         // alert(touches.length);
                //         //identifier
                //         // for(var i=0;i<=touches.length;i++ ){
                //         // $('#test').val(touches.length);
                //
                //     }, false);
                //     self.stage.addEventListener('pressup', function(up_e) {
                //         up_e.preventDefault();
                //         touches = up_e.nativeEvent.changedTouches;
                //         console.log(touches);
                //         self.config.speed=0;
                //         // alert(touches.length);
                //         self.sendUserInfo();
                //         // if(touches.length>=1){
                //         self.sprites['game']['btn_merge'].alpha=1;
                //         self.sprites['game']['btn_divide'].alpha=1;
                //         if(self.config.screen=='landscape'){
                //             self.sprites['game']['btn_move'].initPosition(
                //                 self.data.json['game'].landscape['btn_move'].x,
                //                 self.data.json['game'].landscape['btn_move'].y,
                //                 self.data.json['game'].landscape['btn_move'].regX,
                //                 self.data.json['game'].landscape['btn_move'].regY,
                //                 self.size.real.width,
                //                 self.size.real.height,
                //                 self.ratio,
                //                 self.ratio
                //             );
                //         }else {
                //             self.sprites['game']['btn_move'].initPosition(
                //                 self.data.json['game'].positions['btn_move'].x,
                //                 self.data.json['game'].positions['btn_move'].y,
                //                 self.data.json['game'].positions['btn_move'].regX,
                //                 self.data.json['game'].positions['btn_move'].regY,
                //                 self.size.real.width,
                //                 self.size.real.height,
                //                 self.ratio,
                //                 self.ratio
                //             );
                //         }
                //         // }
                //     }, false);
                // });
                // self.sprites['game']['btn_move'].addEventListener("mousedown", function (e) {
                //     self.config.downX=self.sprites['game']['btn_move'].x;
                //     if(self.config.screen=='landscape'){
                //         self.config.downY=self.sprites['game']['btn_move'].y+0.08*self.size.real.height;
                //     }else {
                //         self.config.downY=self.sprites['game']['btn_move'].y+0.043*self.size.real.height;
                //     }
                // });

                var btn_move=self.sprites['game']['btn_move'];
                var X,Y;
                self.sprites['game']['btn_move'].addEventListener("mousedown", function (e) {
                    self.config.downX=self.sprites['game']['btn_move'].x;
                    if(self.config.screen=='landscape'){
                        self.config.downY=self.sprites['game']['btn_move'].y+0.08*self.size.real.height;
                    }else {
                        self.config.downY=self.sprites['game']['btn_move'].y+0.043*self.size.real.height;
                    }
                });
                self.sprites['game']['btn_move'].addEventListener("pressmove", function (e) {
                    var direction=GetSlideDirection( self.config.downX,self.config.downY,e.stageX,e.stageY);
                    self.config.angle=direction[0];
                    self.config.position=direction[1];

                    if(direction[2]<=50){
                        btn_move.x=e.stageX;
                        btn_move.y=e.stageY;
                    }else {
                        btn_move.x=self.config.downX + Math.sin(2*Math.PI / 360*self.config.angle) * 50;
                        btn_move.y=self.size.real.height-(self.config.downY+Math.cos(2*Math.PI/360*self.config.angle)*50);
                    }
                    X=btn_move.x-self.config.downX;
                    Y=btn_move.y-self.config.downY;
                    if (self.config.isCompare == false) {
                        self.config.isCompare = true;
                        self.lastVector.x = X;
                        self.lastVector.y = Y;
                    } else {
                        self.curVector.x = X;
                        self.curVector.y = Y;
                        self.config.angle=CustomCompareVector(self.lastVector, self.curVector);
                        if (self.config.angle>5) {
                            self.lastVector.x = self.curVector.x;
                            self.lastVector.y = self.curVector.y;
                            //出发发送数据：curVector2；
                            self.sendUserInfo();
                            // moveFunc(self.curVector);
                            // console.log("%c" + "现在的度数大于5度了", "color:#DB7093");
                        }
                    }
                    self.config.direction_move=direction[2];
                });
                self.sprites['game']['btn_move'].addEventListener("pressup", function () {
                    if(self.config.screen=='landscape'){
                        self.sprites['game']['btn_move'].initPosition(
                            self.data.json['game'].landscape['btn_move'].x,
                            self.data.json['game'].landscape['btn_move'].y,
                            self.data.json['game'].landscape['btn_move'].regX,
                            self.data.json['game'].landscape['btn_move'].regY,
                            self.size.real.width,
                            self.size.real.height,
                            self.ratio,
                            self.ratio
                        );
                    }else {
                        self.sprites['game']['btn_move'].initPosition(
                            self.data.json['game'].positions['btn_move'].x,
                            self.data.json['game'].positions['btn_move'].y,
                            self.data.json['game'].positions['btn_move'].regX,
                            self.data.json['game'].positions['btn_move'].regY,
                            self.size.real.width,
                            self.size.real.height,
                            self.ratio,
                            self.ratio
                        );
                    }
                });
                // self.sprites['game']['btn_move'].addEventListener("click ", self.events['game'].sprites['btn_move']);
                // self.sprites['game']['btn_divide'].addEventListener("mousedown",function (e) {
                //     console.log(e);
                //     self.sprites['game']['btn_divide'].alpha=0.7;
                //     self.config.speed=-1;
                //     self.sendUserInfo();
                // });
                // self.sprites['game']['btn_divide'].addEventListener("pressup",function () {
                //     self.sprites['game']['btn_divide'].alpha=1;
                //     self.config.speed=0;
                //     self.sendUserInfo();
                // });
                // // this.events[view].sprites['btn_divide']
                // self.sprites['game']['btn_merge'].addEventListener("mousedown", function () {
                //     self.sprites['game']['btn_merge'].alpha=0.7;
                //     console.log('btn_merge');
                //     self.config.speed=1;
                //     self.sendUserInfo();
                // });
                // self.sprites['game']['btn_merge'].addEventListener("pressup",function () {
                //     self.sprites['game']['btn_merge'].alpha=1;
                //     self.config.speed=0;
                //     self.sendUserInfo();
                // });


                if (this.events['game']) {
                    if (this.events['game'].sprites) {

                    }
                }
            }
            else{
                console.log(this.sprites[view]);
                for (var key in this.sprites[view]) {
                    if (this.data.json[view].excepts) {
                        console.log(this.config.screen);
                        if (this.data.json[view].excepts["rank"] && this.data.json[view].excepts["rank"][this.config.rank][key]) {
                            continue;
                        }
                    }
                    if (this.events[view]) {
                        if (this.events[view].sprites) {
                            if (this.events[view].sprites[key]) {
                                this.sprites[view][key].addEventListener("mousedown", this.events[view].sprites[key]);
                            }
                        }
                    }
                    container.addChild(this.sprites[view][key]);
                    if(view=='fail'){
                        var scoreText = new createjs.Text(this.config.score, "60px Arial", "#ffffff");
                        scoreText.initPosition(0.22, 0.6, 0.5, 0.723, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        var eatNumsText = new createjs.Text(this.config.eatNums, "60px Arial", "#ffffff");
                        eatNumsText.initPosition(0.5, 0.6, 0.5, 0.723, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        var timeText = new createjs.Text(this.config.time, "60px Arial", "#ffffff");
                        timeText.initPosition(0.78, 0.6, 0.5, 0.723, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        if(this.config.screen=="landscape") {
                            scoreText.x=this.size.real.width * 0.325;
                            eatNumsText.x=this.size.real.width * 0.5;
                            timeText.x=this.size.real.width * 0.675;
                            border_time.y=border_score.y=border_eat.y= this.size.real.height * 0.674;
                        }else {
                            scoreText.y=eatNumsText.y=timeText.y=0.51*this.size.real.height;
                        }
                        container.addChild(scoreText,eatNumsText,timeText);
                    }
                    if(view=='timeout'){
                        var scoreText = new createjs.Text(this.config.score, "60px Arial", "#ffffff");
                        scoreText.initPosition(0.24, 0.62, 0.723, 0.5, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        var eatNumsText = new createjs.Text(this.config.eatNums, "60px Arial", "#ffffff");
                        eatNumsText.initPosition(0.51, 0.62,0.723, 0.5, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        var timeText = new createjs.Text(this.config.time, "60px Arial", "#ffffff");
                        timeText.initPosition(0.8, 0.62, 0.723, 0.5, this.size.real.width, this.size.real.height, this.ratio, this.ratio);
                        if(this.config.screen=="landscape") {
                            scoreText.x=this.size.real.width * 0.34;
                            eatNumsText.x=this.size.real.width * 0.51;
                            timeText.x=this.size.real.width * 0.69;
                            border_time.y=border_score.y=border_eat.y= this.size.real.height * 0.674;
                        }else {
                            scoreText.y=eatNumsText.y=timeText.y=this.size.real.height * 0.3;
                            border_time.y=border_score.y=border_eat.y= this.size.real.height * 0.33;
                        }
                        container.addChild(border_eat,border_score,border_time,scoreText,eatNumsText,timeText);
                    }
                }
            }
        }
        this.stage.removeAllChildren();
        this.stage.addChild(this.views[view]);
        if (this.onViewShow[view]) {
            this.onViewShow[view](view);
        }
    };
    this.initUI = function () {
        this.loadAssets();
        console.log(this.config.screen);
        for (var view in this.views) {
            if (this.data.json[view]) {
                for (var key in this.sprites[view]) {
                    this.sprites[view][key].scaleX = this.ratio;
                    this.sprites[view][key].scaleY = this.ratio;
                    if(this.config.screen=="portrait") {
                        if (this.data.json[view].positions) {
                            if (this.data.json[view].positions[key]) {
                                this.sprites[view][key].initPosition(
                                    this.data.json[view].positions[key].x,
                                    this.data.json[view].positions[key].y,
                                    this.data.json[view].positions[key].regX,
                                    this.data.json[view].positions[key].regY,
                                    this.size.real.width,
                                    this.size.real.height,
                                    this.ratio,
                                    this.ratio
                                );
                            }
                        }
                    }else if(this.config.screen=="landscape"){
                        if (this.data.json[view].landscape) {
                            if (this.data.json[view].landscape[key]) {
                                this.sprites[view][key].initPosition(
                                    this.data.json[view].landscape[key].x,
                                    this.data.json[view].landscape[key].y,
                                    this.data.json[view].landscape[key].regX,
                                    this.data.json[view].landscape[key].regY,
                                    this.size.real.width,
                                    this.size.real.height,
                                    this.ratio,
                                    this.ratio
                                );
                            }
                        }
                    }
                }
                if (this.sprites[view]["bg"]) {
                    this.sprites[view]["bg"].initPosition(
                        0.5,
                        0.723,
                        0.5,
                        0.723,
                        this.size.real.width,
                        this.size.real.height,
                        this.ratioX,
                        this.ratioY
                    );
                }
            }
        }
        return this;
    };
    this.loadAssets = function () {
        this.sprites = {};
        this.spriteSheets = {};
        for (var view in this.views) {
            if (this.data.json[view]) {
                this.sprites[view] = {};
                this.spriteSheets[view] = new createjs.SpriteSheet(this.data.json[view]);
                for (var sprite in this.data.json[view].animations) {
                    this.sprites[view][sprite] = new createjs.Sprite(this.spriteSheets[view], sprite);
                }
            }
        }
        this.debug.log(this.sprites);
        this.debug.log(this.spriteSheets);
        return this;
    };
    this.preload = function () {
        this.debug.info('preload_files');
        // this.debug.log(this.config.preload.files);
        if (this.config.preload.files) {
            return new Preloader(this.config.preload);
        }
        this.debug.error('preload_files is undefined');
        return false;
    };
    this.events = {
        start: {
            views: function (event) {
                // return self.showView("lang_select");
            },
            sprites: {
                btn_start:function () {
                    self.config.name=$('#name').val();
                    $('#name').hide();
                    userInfo.userName=self.config.name;
                    userInfo.again=self.config.restart;
                    self.sendUserInfo(userInfo);
                    $('#divide').show();
                    $('#merge').show();
                    return self.showView("game");
                }
            }
        },
        game: {
            sprites: {
                btn_move:function () {
                    console.log('111');
                    // return self.showView("fail");
                },
                btn_merge:function () {
                    console.log('fhjdhfdf111111111111');
                    // return self.showView("timeout");
                },
                btn_divide:function(){
                    console.log('djsdsd');
                    // return self.showView("fail");
                }
            },
            views: function (event) {
                // return self.showView("action");
            }
        },
        timeout: {
            sprites: {
                btn_share:function () {
                    console.log('share');
                    $('#share_bg').show();
                }
            },
            views: function (event) {
                // $('#share_bg').hide();
                // return self.showView("animation");
            }
        },
        fail: {
            sprites: {
                "btn_share":function (e) {
                    console.log('share');
                    $('#share_bg').show();
                    // return self.showView("fail");
                },
                "btn_continue":function (e) {
                    self.config.restart=true;
                    return self.showView("start");
                }
            },
            views:function () {
                // $('#share_bg').hide();
            }
        }
    };
    this.animateFlash = function (target, callback) {
        target.alpha = 0.1;
        createjs.Tween.get(target)
            .to({alpha: 1}, 200)
            .to({alpha: 0}, 200)
            .to({alpha: 1}, 200)
            .call(function () {
                if (callback) {
                    return callback();
                }
            });
        return true;
    };

    this.animateFlashLoop=function (target) {
        console.log("Looop");
        createjs.Tween.get(target)
            .to({alpha: 0.5}, 1200)
            .to({alpha: 1}, 1200)
            .call(animateFlashLoop(target));
    };

    this.animateElement = function (view) {
        console.log(self.data.json);
        if (self.data.json[view]) {
            if (self.data.json[view].tweens) {
                var timeline = new createjs.Timeline();
                for (var key in self.data.json[view].tweens) {
                    var to = {};
                    for (var prop in self.data.json[view].tweens[key]["from"]) {
                        to[prop] = self.sprites[view][key][prop];
                        switch (prop) {
                            case "x":
                                self.sprites[view][key].initPosition(
                                    self.data.json[view].tweens[key]["from"][prop],
                                    self.data.json[view].positions[key].y,
                                    self.data.json[view].positions[key].regX,
                                    self.data.json[view].positions[key].regY,
                                    self.size.real.width,
                                    self.size.real.height,
                                    self.ratio,
                                    self.ratio
                                );
                                break;
                            case "y":
                                self.sprites[view][key].initPosition(
                                    self.data.json[view].positions[key].x,
                                    self.data.json[view].tweens[key]["from"][prop],
                                    self.data.json[view].positions[key].regX,
                                    self.data.json[view].positions[key].regY,
                                    self.size.real.width,
                                    self.size.real.height,
                                    self.ratio,
                                    self.ratio);
                                break;
                            default:
                                self.sprites[view][key][prop] = self.data.json[view].tweens[key]["from"][prop];
                        }
                        timeline.addTween(createjs.Tween
                            .get(self.sprites[view][key], {loop: self.data.json[view].tweens[key]["loop"] || false})
                            .wait(self.data.json[view].tweens[key]["delay"] || 0)
                            .to(to, self.data.json[view].tweens[key]["duration"] || 1000));
                    }
                }
            }
        }
    };
    this.onViewShow = {
        start: function (view) {
            console.log(view);
            $('#name').show();
                if(self.config.screen=='landscape'){
                    // $('#name').css("top","60%");
                    // $('#name').hide();
                    // self.views[view].removeChild(self.sprites[view].bg_name);
                }else {
                    // $('#name').show();
                }


        },
        game: function (view) {


        },
        timeout: function (view) {

        },
        fail:function (view) {

        }
    };

}

function getRandomInt(max, min) {
    min = min || 0;
    return Math.floor((Math.random() * (max - min)) + min);
}

});
createjs.DisplayObject.prototype.initPosition = function (x, y, regX, regY, screenWidth, screenHeight, scaleX, scaleY) {
    scaleX = scaleX || 1;
    scaleY = scaleY || 1;
    // console.log(this);
    this.setTransform(
        screenWidth * x,
        screenHeight * y,
        scaleX, scaleY,
        0, 0, 0,
        this.getBounds().width * regX,
        this.getBounds().height * regY
    );
};

